from models import HookModel,User
from django.conf import settings
import random
import redis
from math import cos,sin,atan2,sqrt,radians,asin
from django.contrib.sessions.backends.db import SessionStore


def session_to_user(session_id):
    sess = SessionStore(session_key=session_id)
    pk = sess.get('_auth_user_id')
    return User.objects.get(pk=pk)
    

def get_or_none(model, **kw):
    """
    """
    try:
        obj = model.objects.filter(**kw).order_by('-id')[0]
        return obj
    except IndexError:
        return None


def hook_all(func):
    def _func(request,*args,**kw):
        if not getattr( settings,'LOCAL',None):
            head=request.META
            body = request.body
            path =request.get_full_path()
            method= request.method
            hh = HookModel.objects.create(head=head,body=body,path=path,method=method)
            hh.save()
        
            try:
                rt = func(request,*args,**kw)
                hh.rsp=rt.content
                hh.save() 
                return rt
            except Exception as e:
                hh.rsp=str(e)
                hh.save()
                raise e
        else:
            return func(request,*args,**kw)
    return _func

redis_conn = None

def redis_init():
    global redis_conn
    if not isinstance(redis_conn, redis.client.StrictRedis):
        redis_conn = redis.StrictRedis(settings.REDIS_HOST,
                                       settings.REDIS_PORT,
                                       settings.REDIS_DB)
    return redis_conn

redis_init()

def get_random_word(length=10):
    pool='1234567890abcdefghijklmnopqrstuvwxyz'
    return ''.join([random.choice(pool) for i in range(length)])


def distance(jd1,wd1,jd2,wd2):
    jd1=radians(jd1)
    wd1=radians(wd1)
    jd2=radians(jd2)
    wd2=radians(wd2)
    
    a= wd1-wd2
    b=jd1-jd2
    s= 2 * asin(sqrt( sin(a/2)**2 + cos(wd1)*cos(wd2)* sin(b/2)**2))
    s = s* 6367000
    return s

#def distance(jd1,wd1,jd2,wd2):
    #hsinX=sin(jd1-jd2)*0.5
    #hsinY=sin(wd1-wd2)*0.5
    #h=hsinY**2 + cos(jd1)+cos(jd2)*hsinX**2
    #return 2*atan2(sqrt(h),sqrt(1-h))*6367000
    
    ##double hsinX = Math.sin((lon1 - lon2) * 0.5);
        ##double hsinY = Math.sin((lat1 - lat2) * 0.5);
        ##double h = hsinY * hsinY +
            ##(Math.cos(lat1) * Math.cos(lat2) * hsinX * hsinX);
        ##return 2 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h)) * 6367000;    